package com.admin.system.modules.system.service.impl;

import com.admin.common.utils.PageResult;
import com.admin.common.utils.PageUtil;
import com.admin.core.dto.DictQueryDTO;
import com.admin.core.entity.SysDict;
import com.admin.core.entity.SysDictDetail;
import com.admin.core.mapper.DictMapper;
import com.admin.system.modules.system.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * @author sq-lan
 */
@Service
@RequiredArgsConstructor
public class DictServiceImpl extends ServiceImpl<DictMapper, SysDict> implements DictService {

    @Override
    public PageResult<SysDict> paging(DictQueryDTO dto) {
        PageHelper.startPage(dto.getCurrent(), dto.getSize());
        LambdaQueryWrapper<SysDict> wrapper = createWrapper(dto);
        List<SysDict> list = baseMapper.selectList(wrapper);
        return PageUtil.toPageHelper(list);
    }

    @Override
    public List<SysDict> list(DictQueryDTO dto) {
        LambdaQueryWrapper<SysDict> wrapper = createWrapper(dto);
        return baseMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(Set<Long> ids) {
        // 删除字典
        baseMapper.deleteBatchIds(ids);
        Wrappers.<SysDictDetail>lambdaQuery().in(SysDictDetail::getDictId, ids);
    }

    private LambdaQueryWrapper<SysDict> createWrapper(DictQueryDTO dto) {
        LambdaQueryWrapper<SysDict> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.hasText(dto.getBlurry())) {
            wrapper.and(w -> w.like(SysDict::getName, dto.getBlurry()).or().like(SysDict::getDescription, dto.getBlurry()));
        }
        return wrapper;
    }

}
